"""
===============================
@author     : yaoruiqi

@Time       : 2023/3/20 12:42

@version    : V

@introduce  :

@change     : 
===============================
"""
from celery import shared_task
from django.core.cache import cache
from loguru import logger

from api.public_methods import get_access_token
from api.wechat_api import get_subscription_user_info
from app_subscription_account.models import SubscriptionUser


@shared_task
def check_user_exists(openid: str):
    """
    检测用户信息是否存在于公众号用户表
    @param openid: 用户openid
    @return:
    """
    try:
        with cache.lock(f'check_user_exists:{openid}', blocking_timeout=3, timeout=5):
            user_obj = SubscriptionUser.objects.filter(openid=openid)
            if user_obj:
                logger.info(f'用户存在 openid：{openid}')
            else:
                access_token = get_access_token(service_name='subscription_tips')
                user_info = get_subscription_user_info.get_user_info(access_token=access_token, openid=openid)
                if user_info:
                    SubscriptionUser.objects.create(
                        openid=user_info['openid'], subscribe=user_info['subscribe'], subscribe_time=user_info['subscribe_time'],
                        remark=user_info['remark'], groupid=user_info['groupid'], tagid=';'.join(user_info['tagid_list']),
                        subscribe_scene=user_info['subscribe_scene'], subscription='tips'
                    )
                logger.info(f'用户信息不存在，补全用户信息 openid：{openid}')
    except Exception as e:
        logger.exception(f'查询用户信息失败，{e}')
